// Author: Mark Richardson
// Date finalized: 06/24/2022
// Purpose: Non-centered Bayesian hierarchical item response model for latent partisan disagreement

data {
  
  int K_freq; // number of response categories
  
  int K_strg; // number of response categories
  
  int J; // number of agencies
  
  int M; // number of missions
  
  int N; // number of observations
  
  int<lower = 1, upper = J> jj[N]; // agency index
  
  int<lower = 1, upper = M> mm[N]; // mission index
  
  int<lower = 1, upper = K_freq> y_freq[N]; // responses (array of N constrained integers)
  
  int<lower = 1, upper = K_strg> y_strg[N]; // responses (array of N constrained integers)
  
  int mu_group[J]; // mission_index for each agency
  
}
 
parameters {
  
  ordered[K_freq - 1] c_freq; // cutpoints
  
  ordered[K_strg - 1] c_strg; // cutpoints

  vector[J] theta_raw; // latent disagreement
  
  vector[M] mu; // mission means
  
  vector<lower = 0>[M] tau; // scale of mission-level disagreement
  
  real<lower = 0> delta_freq; // Coefficients on latent trait
  
  real<lower = 0> delta_strg;

}

transformed parameters {
  
  vector[J] theta;
  
  for (j in 1:J) {
    
    theta[j] = mu[mu_group[j]] + tau[mu_group[j]] * theta_raw[j];
    
    }

  }

model {
  
  theta_raw ~ std_normal();
  
  tau ~ normal(0, 5);
  
  mu ~ std_normal();
  
  c_freq ~ normal(0, 5);
  
  c_strg ~ normal(0, 5);
  
  delta_freq ~ normal(0, 5);
  
  delta_strg ~ normal(0, 5);
  
  for (n in 1:N) {
    
    y_freq[n] ~ ordered_probit(delta_freq * theta[jj[n]], c_freq);
    
    y_strg[n] ~ ordered_probit(delta_strg * theta[jj[n]], c_strg);
    
  }
}

